## Evaluation of Wahlomat experiment -----

# load packages
source("packages.r")


## data import ------------------------------

load("../data/yougov_panel_ger_wide_wahlomat_prep.RData")


## plot treatment compliance -------------------------

# cross tab tracked/reported use with survey encouragement
ctable(waves_df_wide$wahlomat_use_combined, waves_df_wide$wahlomat_encouragement, prop = "n")
ctable(waves_df_wide$wahlomat_encouragement, waves_df_wide$wahlomat_use_combined)

tabyl(waves_df_wide$wahlomat_use_combined[waves_df_wide$wave4 == T])

# melt data, with dichotomous encouragement variable based on tracking data (+ reported data if tracking data is missing)
out_df <- dplyr::select(waves_df_wide, wahlomat_use_combined, wahlomat_encouragement)  %>% 
  melt(id.var="wahlomat_use_combined") %>%
  filter(!is.na(value), !is.na(wahlomat_use_combined)) %>%  # Remove NA
  group_by(wahlomat_use_combined, variable, value) %>%
  summarise(count_single = n()) %>% 
  group_by(wahlomat_use_combined) %>% 
  mutate(count_use = sum(count_single)) %>%
  group_by(value) %>% 
  mutate(count_encouragement = sum(count_single)) %>%
  group_by(wahlomat_use_combined) %>% 
  mutate(percent_encouragement = round(count_single/sum(count_single)*100, 0)) %>%
  group_by(value) %>% 
  mutate(percent_use = round(count_single/sum(count_single)*100, 0))

# prepare labels
val_labels(out_df$wahlomat_use_combined) <- c(`Wahl-O-Mat\nused` = 1, `Wahl-O-Mat  \nnot used ` = 0)
val_labels(out_df$value) <- c(`Encouragement` = 1, `Control` = 0) 

# generate plot
p <- ggplot(data = out_df, aes(as_factor(value), percent_use)) +
  geom_bar(aes(fill = forcats::fct_rev(as_factor(wahlomat_use_combined))), position = "stack", stat = "identity") +
  geom_text(aes(x = 2, y = 17, label = "Never-takers"), color = "white", family = "sans") + 
  geom_text(aes(x = 1, y = 85, label = "Always-takers"), color = "white", family = "sans") + 
  scale_fill_manual(values = c("#5e3c99", "#e66101")) + 
  scale_y_continuous(labels = function(x) paste0(x, "%"), limits = c(0, 100)) + 
  scale_x_discrete(labels =  function(x) paste0(x, "\n", "n = ", out_df$count_encouragement)[1:2]) + 
  coord_flip() + 
  theme_ipsum_rc() + 
  theme(axis.title.x = element_text(size = 15),
        axis.title.y = element_text(size = 15),
        legend.position="bottom",
        legend.title = element_blank(),
        legend.margin=margin(-10,0,0,0),
        legend.spacing.x = unit(.25, 'cm'),
        legend.box.margin=margin(-10,-10,-10,-10),
        plot.margin=unit(c(0.1,0.1,0.5,0.1),"cm")) + 
  xlab("") + ylab("") 
p
# save plot
ggsave(p, file = "../output/wahlomat_treatment_compliance.png", width = 3, height = 1, units = "cm", dpi = 300, scale = 5)



## plot reported Wahlomat recommendations -----------------------------

# prepare advice data
out_df <- dplyr::select(waves_df_wide, secondvote_3, wahlomat_advice_combined) %>% 
  .[complete.cases(.),] %>%
  group_by(secondvote_3, wahlomat_advice_combined) %>%
  summarise(advice_count = n()) %>%
  mutate(advice_percent = round(advice_count/sum(advice_count)*100, 1)) %>%
  group_by(secondvote_3) %>%
  mutate(preference_count = sum(advice_count))

# fill up empty rows
added_vars <- expand.grid(unique(waves_df_wide$secondvote_3), unique(waves_df_wide$wahlomat_advice_combined)) %>% drop_na()
names(added_vars) <- c("secondvote_3", "wahlomat_advice_combined")
out_df <- merge(out_df, added_vars, by = c("secondvote_3", "wahlomat_advice_combined"), all = TRUE)
out_df[is.na(out_df)] <- 0


# generate plot
p <- ggplot(data = out_df, aes(as_factor(secondvote_3), advice_percent)) + 
  geom_bar(aes(fill = as_factor(wahlomat_advice_combined)), position = "dodge", stat = "identity") +
  geom_text(data = filter(out_df, wahlomat_advice_combined == 1), aes(y = 76, label = paste0("n = ", preference_count))) +
  scale_fill_manual(values = colors_parties_df$colors[1:6]) +
  scale_y_continuous(labels = function(x) paste0(x, "%"), limits = c(0, max(out_df$advice_percent) + 5)) + 
  guides(fill = guide_legend(nrow = 1)) + 
  theme_ipsum_rc() + 
  theme(axis.title.x = element_text(size = 12),
        axis.title.y = element_text(size = 12),
        legend.position= "bottom",
        legend.title = element_blank(),
        legend.margin = margin(-10,0,0,0),
        legend.spacing.x = unit(.25, 'cm'),
        legend.box.margin = margin(-10,-10,-10,-10),
        plot.margin = unit(c(0.1,0.1,0.5,0.1),"cm")) + 
  xlab("Respondents'\nparty identification") + ylab("Share of top overlapping party") 
p
# save plot
ggsave(p, file = "../output/wahlomat_advice_by_preference.png", width = 6, height = 3, units = "cm", dpi = 300, scale = 5)



## plot reported Wahlomat anti-recommendations -----------------------------

# prepare anti-advice (least-recommended party) data
out_df <- dplyr::select(waves_df_wide, secondvote_3, wahlomat_antiadvice) %>% 
  .[complete.cases(.),] %>%
  group_by(secondvote_3, wahlomat_antiadvice) %>%
  summarise(antiadvice_count = n()) %>%
  mutate(antiadvice_percent = round(antiadvice_count/sum(antiadvice_count)*100, 1)) %>%
  group_by(secondvote_3) %>%
  mutate(preference_count = sum(antiadvice_count))

# fill up empty rows
added_vars <- expand.grid(unique(waves_df_wide$secondvote_3), unique(waves_df_wide$wahlomat_antiadvice)) %>% drop_na()
names(added_vars) <- c("secondvote_3", "wahlomat_antiadvice")
out_df <- merge(out_df, added_vars, by = c("secondvote_3", "wahlomat_antiadvice"), all = TRUE)
out_df[is.na(out_df)] <- 0

# generate plot
p <- ggplot(data = out_df, aes(as_factor(secondvote_3), antiadvice_percent)) + 
  geom_bar(aes(fill = as_factor(wahlomat_antiadvice)), position = "dodge", stat = "identity") +
  geom_text(data = filter(out_df, wahlomat_antiadvice == 1), aes(y = 76, label = paste0("n = ", preference_count))) +
  scale_fill_manual(values = colors_parties_df$colors[1:6]) +
  scale_y_continuous(labels = function(x) paste0(x, "%"), limits = c(0, max(out_df$antiadvice_percent) + 5)) + 
  guides(fill = guide_legend(nrow = 1)) + 
  theme_ipsum_rc() + 
  theme(axis.title.x = element_text(size = 12),
        axis.title.y = element_text(size = 12),
        legend.position="bottom",
        legend.title = element_blank(),
        legend.margin = margin(-10,0,0,0),
        legend.spacing.x = unit(.25, 'cm'),
        legend.box.margin = margin(-10,-10,-10,-10),
        plot.margin = unit(c(0.1,0.1,0.5,0.1),"cm")) + 
  xlab("Respondents'\nparty identification") + ylab("Share of bottom overlapping party") 
p
# save plot
ggsave(p, file = "../output/wahlomat_antiadvice_by_preference.png", width = 6, height = 3, units = "cm", dpi = 300, scale = 5)


## how many people get their second-vote preference recommended?
table(as_factor(waves_df_wide$secondvote_3))
tabyl(as_factor(waves_df_wide$wahlomat_advice_combined))
table(waves_df_wide$secondvote_3 == waves_df_wide$wahlomat_advice_combined)
prop.table(table(waves_df_wide$secondvote_3 == waves_df_wide$wahlomat_advice_combined))



## descriptive statistics of key variables -----------------------------

# define groups
no_vaa_control_n <- sum(waves_df_wide$wahlomat_use_combined == 0 & waves_df_wide$wahlomat_encouragement == 0)
no_vaa_treatment_n <- sum(waves_df_wide$wahlomat_use_combined == 0 & waves_df_wide$wahlomat_encouragement == 1)
vaa_control_n <- sum(waves_df_wide$wahlomat_use_combined == 1 & waves_df_wide$wahlomat_encouragement == 0)
vaa_treatment_n <- sum(waves_df_wide$wahlomat_use_combined == 1 & waves_df_wide$wahlomat_encouragement == 1)

group_labels <- c(paste0('Not encouraged,\nno VAA use\n(n = ', no_vaa_control_n, ")"),
                  paste0('Encouraged,\nno VAA use\n(n = ', no_vaa_treatment_n, ")"),
                  paste0('Not encouraged,\nVAA use\n(n = ', vaa_control_n, ")"),
                  paste0('Encouraged,\nVAA use\n(n = ', vaa_treatment_n, ")")
)
waves_df_wide <- waves_df_wide %>%
  mutate(takers = case_when(
                          wahlomat_use_combined == 0 & wahlomat_encouragement == 0 ~ group_labels[1],
                          wahlomat_use_combined == 0 & wahlomat_encouragement == 1 ~ group_labels[2],
                          wahlomat_use_combined == 1 & wahlomat_encouragement == 0 ~ group_labels[3],
                          TRUE ~ group_labels[4]))

table(waves_df_wide$takers)
ctable(waves_df_wide$wahlomat_use_combined, waves_df_wide$wahlomat_encouragement)
waves_df_wide$takers <- factor(waves_df_wide$takers, levels = group_labels, ordered = TRUE)

# create summary statistics
sum_df <- waves_df_wide %>% 
  group_by(takers) %>%
  summarize(voted_2017_yesno = mean(voted_2017_yesno, na.rm = TRUE),
            wahlomat_perceivedpos_correct_avg = mean(wahlomat_perceivedpos_correct_avg, na.rm = TRUE),
            secondvote_3to4 = mean(secondvote_3to4, na.rm = TRUE),
            news_count = mean(news_count, na.rm = TRUE),
            political_posts_count = mean(political_posts_count, na.rm = TRUE),
            political_tweets = mean(political_tweets, na.rm = TRUE),
            likelihoodvote_3to4 = mean(likelihoodvote_3to4, na.rm = TRUE),
            votecertainty_3to4 = mean(votecertainty_3to4, na.rm = TRUE),
            polinterest_1to4 = mean(polinterest_1to4, na.rm = TRUE),
            mobilized_2017 = mean(mobilized_2017, na.rm = TRUE),
            efficacy = mean(efficacy, na.rm = TRUE),
            scaloparties_cdu_3to4 = mean(scaloparties_cdu_3to4, na.rm = TRUE),
            scaloparties_spd_3to4 = mean(scaloparties_spd_3to4, na.rm = TRUE),
            scaloparties_fdp_3to4 = mean(scaloparties_fdp_3to4, na.rm = TRUE),
            scaloparties_gru_3to4 = mean(scaloparties_gru_3to4, na.rm = TRUE),
            scaloparties_lin_3to4 = mean(scaloparties_lin_3to4, na.rm = TRUE),
            scaloparties_afd_3to4 = mean(scaloparties_afd_3to4, na.rm = TRUE),
            vote_cdu = mean(vote_cdu, na.rm = TRUE),
            vote_spd = mean(vote_spd, na.rm = TRUE),
            vote_fdp = mean(vote_fdp, na.rm = TRUE),
            vote_gru = mean(vote_gru, na.rm = TRUE),
            vote_lin = mean(vote_lin, na.rm = TRUE),
            vote_afd = mean(vote_afd, na.rm = TRUE),
            candidate_knowledge_2to5 = mean(candidate_knowledge_2to5, na.rm = TRUE),
            civic_knowledge_2to5 = mean(civic_knowledge_2to5, na.rm = TRUE),
            event_knowledge_4 = mean(event_knowledge.4, na.rm = TRUE),
            vote_undecided_3 = mean(vote_undecided_3, na.rm = TRUE),
            likelihoodvote_3_below9 = mean(likelihoodvote_3_below9, na.rm = TRUE)
            )
sum_df$y = 1

## function to plot descriptives
gg_dotplot <- function(data, variable, xmin, xmax, title, var.scale, var.measured, add.legend = FALSE, title.pos = "axis") {
## function to plot descriptives
  # set plot parameters
  if(add.legend == TRUE){
    legend.position <- "bottom"
    plot.margin <- unit(c(0.1,0.1,0.5,0.1),"cm")
    plot.height <- .65
  }else if(add.legend == FALSE){
    legend.position <- "none"
    plot.margin <- unit(c(0.1,0.1,0.1,0.1),"cm")
    plot.height <- .5
  }
  if(title.pos == "axis") {
    axis.title.y = element_text(angle = 0, vjust = 0.5, hjust = 1, face = "bold")
    y.title <- paste0(title, "\n", "Scale: ", var.scale, "\n", var.measured)
    plot.title <- NULL
    plot.subtitle <- NULL
  }else if(title.pos == "top") {
    y.title = ""
    axis.title.y = element_blank()
    plot.title <- title
    plot.subtitle <- paste0("Scale: ", var.scale, "   Measured: ", var.measured)
    plot.height = 1
  }
  # set up plot
  p <- ggplot(data, aes_string(x = variable, y = 1, label = round(as.data.frame(data)[,variable], 2))) + 
    geom_segment(aes(x = xmin, xend = xmax, y = 1, yend = 1)) + 
    geom_point(aes(color = takers), size = 3) + 
    scale_color_manual(labels = group_labels, values = c("#e66101", "#fdb863", "#b2abd2", "#5e3c99")) +
    geom_text(aes(color = takers), size = 3, vjust = -2) + 
    guides(fill = guide_legend(nrow = 1)) + 
    scale_y_continuous(breaks = NULL, limits = c(.975, 1.025)) + 
    scale_x_continuous(limits = c(xmin, xmax)) +
    labs(y = y.title,
         x = "",
         title = plot.title,
         subtitle = plot.subtitle) + 
    theme_ipsum_rc() + 
    theme(axis.title.x = element_blank(),
          axis.title.y = axis.title.y,
          axis.text.y = element_blank(), 
          axis.text.x = element_text(size = 10),
          legend.position = legend.position,
          legend.title = element_blank(),
          legend.margin = margin(5,0,0,0),
          legend.spacing.x = unit(.25, 'cm'),
          legend.box.margin = margin(-10,-10,-10,-10),
          plot.margin = plot.margin) 
  # save plot
  ggsave(p, file = paste0("../output/means-", variable, ".png"),
         width = 3.5, height = plot.height, units = "cm", dpi = 300, scale = 5)
}

# generate plots
gg_dotplot(data = sum_df, 
           variable = "likelihoodvote_3to4", 
           xmin = 0, 
           xmax = .3, 
           title = "                                          \nChange in\nlikelihood to vote", 
           var.scale = "[-9, 9]",
           var.measured = "Wave 3 to Wave 4\n                                          ")

gg_dotplot(data = sum_df, 
           variable = "mobilized_2017", 
           xmin = 0, 
           xmax = .2, 
           title = "                                          \nMobilized to vote", 
           var.scale = "[0, 1]",
           var.measured = "Wave 1 and Wave 5\n                                          ")

gg_dotplot(data = sum_df, 
           variable = "voted_2017_yesno", 
           xmin = .75, 
           xmax = 1, 
           title = "                                          \nVoted in election", 
           var.scale = "[0, 1]",
           var.measured = "Wave 5\n                                          ")

gg_dotplot(data = sum_df, 
           variable = "votecertainty_3to4", 
           xmin = .2, 
           xmax = .5, 
           title = "                                          \nChange in\nvote certainty", 
           var.scale = "[-9, 9]",
           var.measured = "Wave 3 to Wave 4\n                                          ")

gg_dotplot(data = sum_df, 
           variable = "secondvote_3to4", 
           xmin = 0, 
           xmax = .25, 
           title = "                                          \nSwitched\nvote choice", 
           var.scale = "[0, 1]",
           var.measured = "Wave 3 to Wave 4\n                                          ")

gg_dotplot(data = sum_df, 
           variable = "vote_undecided_3", 
           xmin = 0, 
           xmax = .2, 
           title = "                                          \nUndecided\nvote choice", 
           var.scale = "[0,1]",
           var.measured = "Wave 3\n                                          ")

gg_dotplot(data = sum_df, 
           variable = "likelihoodvote_3_below9", 
           xmin = 0, 
           xmax = .3, 
           title = "                                          \nUndecided to vote", 
           var.scale = "[0,1]",
           var.measured = "Wave 3\n                                          ")

gg_dotplot(data = sum_df, 
           variable = "efficacy", 
           xmin = -.2, 
           xmax = .2, 
           title = "                                          \nPolitical efficacy", 
           var.scale = "[-3.16, 2.66]",
           var.measured = "Wave 4\n                                          ",
           add.legend = TRUE)

gg_dotplot(data = sum_df, 
           variable = "candidate_knowledge_2to5", 
           xmin = .5, 
           xmax = 1.5, 
           title = "                                          \nChange in\ncandidate recognition", 
           var.scale = "[-9, 9]",
           var.measured = "Wave 2 to Wave 5\n                                          ")

gg_dotplot(data = sum_df, 
           variable = "civic_knowledge_2to5", 
           xmin = .1, 
           xmax = .4, 
           title = "                                          \nChange in\ncivic knowledge", 
           var.scale = "[-2, 2]",
           var.measured = "Wave 2 to Wave 5\n                                          ")

gg_dotplot(data = sum_df, 
           variable = "event_knowledge_4", 
           xmin = 5, 
           xmax = 7, 
           title = "                                          \nEvent knowledge", 
           var.scale = "[0, 10]",
           var.measured = "Wave 4\n                                          ")

gg_dotplot(data = sum_df, 
           variable = "wahlomat_perceivedpos_correct_avg", 
           xmin = .6, 
           xmax = .7, 
           title = "                                          \nIssue knowledge", 
           var.scale = "[0, 1]",
           var.measured = "Wave 4\n                                          ")

gg_dotplot(data = sum_df, 
           variable = "polinterest_1to4", 
           xmin = -.2, 
           xmax = .1, 
           title = "                                          \nChange in\npolitical interest", 
           var.scale = "[-4, 4]",
           var.measured = "Wave 1 to Wave 4\n                                          ")

gg_dotplot(data = sum_df, 
           variable = "news_count", 
           xmin = 0, 
           xmax = 100, 
           title = "                                          \nNews consumption", 
           var.scale = "[0+]",
           var.measured = "Tracking data\n                                          ")

gg_dotplot(data = sum_df, 
           variable = "political_posts_count", 
           xmin = 0, 
           xmax = 3, 
           title = "                                          \nPolitical use,\nFacebook", 
           var.scale = "[0+]",
           var.measured = "Social media data\n                                          ")

gg_dotplot(data = sum_df, 
           variable = "political_tweets", 
           xmin = 0, 
           xmax = 20, 
           title = "                                          \nPolitical use,\nTwitter", 
           var.scale = "[0+]",
           var.measured = "Social media data\n                                          ",
           add.legend = TRUE)


gg_dotplot(data = sum_df, 
           variable = "scaloparties_cdu_3to4", 
           xmin = -.4, 
           xmax = .4, 
           title = "Change in sympathy\ntowards CDU/CSU", 
           var.scale = "[-10, 10]",
           var.measured = "Wave 3 to Wave 4")

gg_dotplot(data = sum_df, 
           variable = "scaloparties_spd_3to4", 
           xmin = -.4, 
           xmax = .4, 
           title = "Change in sympathy\ntowards SPD", 
           var.scale = "[-10, 10]",
           var.measured = "Wave 3 to Wave 4")

gg_dotplot(data = sum_df, 
           variable = "scaloparties_fdp_3to4", 
           xmin = -.4, 
           xmax = .4, 
           title = "Change in sympathy\ntowards FDP", 
           var.scale = "[-10, 10]",
           var.measured = "Wave 3 to Wave 4")

gg_dotplot(data = sum_df, 
           variable = "scaloparties_gru_3to4", 
           xmin = -.4, 
           xmax = .4, 
           title = "Change in sympathy\ntowards Greens", 
           var.scale = "[-10, 10]",
           var.measured = "Wave 3 to Wave 4")

gg_dotplot(data = sum_df, 
           variable = "scaloparties_lin_3to4", 
           xmin = -.4, 
           xmax = .4, 
           title = "Change in sympathy\ntowards Left", 
           var.scale = "[-10, 10]",
           var.measured = "Wave 3 to Wave 4")

gg_dotplot(data = sum_df, 
           variable = "scaloparties_afd_3to4", 
           xmin = -.4, 
           xmax = .4, 
           title = "Change in sympathy\ntowards AfD", 
           var.scale = "[-10, 10]",
           var.measured = "Wave 3 to Wave 4",
           add.legend = TRUE)

gg_dotplot(data = sum_df, 
           variable = "vote_cdu", 
           xmin = 0, 
           xmax = .3, 
           title = "Second vote 2017:\nCDU/CSU", 
           var.scale = "[0, 1]",
           var.measured = "Wave 5")

gg_dotplot(data = sum_df, 
           variable = "vote_spd", 
           xmin = 0, 
           xmax = .3, 
           title = "Second vote 2017:\nSPD", 
           var.scale = "[0, 1]",
           var.measured = "Wave 5")

gg_dotplot(data = sum_df, 
           variable = "vote_fdp", 
           xmin = 0, 
           xmax = .3, 
           title = "Second vote 2017:\nFDP", 
           var.scale = "[0, 1]",
           var.measured = "Wave 5")

gg_dotplot(data = sum_df, 
           variable = "vote_gru", 
           xmin = 0, 
           xmax = .3, 
           title = "Second vote 2017:\nGreens", 
           var.scale = "[0, 1]",
           var.measured = "Wave 5")

gg_dotplot(data = sum_df, 
           variable = "vote_lin", 
           xmin = 0, 
           xmax = .3, 
           title = "Second vote 2017:\nLeft", 
           var.scale = "[0, 1]",
           var.measured = "Wave 5")

gg_dotplot(data = sum_df, 
           variable = "vote_afd", 
           xmin = 0, 
           xmax = .3, 
           title = "Second vote 2017:\nAfD", 
           var.scale = "[0, 1]",
           var.measured = "Wave 5",
           add.legend = TRUE)





## Sample balance --------------------------------

yougov_quota_df <- read_excel("../data/yougov-online-quota.xlsx")
dat <- dplyr::select(waves_df_wide, wahlomat_encouragement, wahlomat_use,
                     gender.1,
                     age.1,
                     educ.1,
                     hhincome.1,
                     polinterest.1,
                     leftright.1,
                     likelihoodvote.1)
survey_quotavars_df <- transmute(dat, wahlomat_encouragement, wahlomat_use, male = (gender.1 == 1),
                                 female = (gender.1 == 2),
                                 age_18_34 = (age.1 >= 18 & age.1 <=34),
                                 age_35_44 = (age.1 >= 35 & age.1 <=44),
                                 age_45_54 = (age.1 >= 45 & age.1 <=54),
                                 age_55_older = (age.1 >= 55),
                                 education_none = (educ.1 == 1 | educ.1 == 5),
                                 education_pre_secondary = (educ.1 == 2),
                                 education_secondary = (educ.1 == 3),
                                 education_high_school = (educ.1 == 4)
)
survey_quotavars_encouragement_df <- survey_quotavars_df %>% group_by(wahlomat_encouragement) %>%
  summarise_all(funs(round(mean(., na.rm=TRUE)*100, 1)))
survey_quotavars_use_df <- survey_quotavars_df %>% group_by(wahlomat_use) %>%
  summarise_all(funs(round(mean(., na.rm=TRUE)*100, 1)))
survey_quotavars_all_df <- survey_quotavars_df %>% 
  summarise_all(funs(round(mean(., na.rm=TRUE)*100, 1)))

yougov_quota_df$full_sample <- survey_quotavars_all_df[,-c(1,2)] %>% as.numeric
yougov_quota_df$wahlomat_encouragement_yes <- filter(survey_quotavars_encouragement_df, wahlomat_encouragement == 1)[,-c(1,2)] %>% as.numeric
yougov_quota_df$wahlomat_encouragement_no <- filter(survey_quotavars_encouragement_df, wahlomat_encouragement == 0)[,-c(1,2)] %>% as.numeric
yougov_quota_df$wahlomat_use_yes <- filter(survey_quotavars_use_df, wahlomat_use == 1)[,-c(1,2)] %>% as.numeric
yougov_quota_df$wahlomat_use_no <- filter(survey_quotavars_use_df, wahlomat_use == 0)[,-c(1,2)] %>% as.numeric

balance_table <- dplyr::select(yougov_quota_df, label2, quota, full_sample, wahlomat_encouragement_no, wahlomat_encouragement_yes, wahlomat_use_no, wahlomat_use_yes)
balance_table <- rbind(data.frame(label2 = "Gender", quota = NA, full_sample = NA, wahlomat_encouragement_no = NA, wahlomat_encouragement_yes = NA, wahlomat_use_no = NA, wahlomat_use_yes = NA, stringsAsFactors = FALSE),
                       balance_table[1:2,],
                       data.frame(label2 = "Age", quota = NA, full_sample = NA, wahlomat_encouragement_no = NA, wahlomat_encouragement_yes = NA, wahlomat_use_no = NA, wahlomat_use_yes = NA, stringsAsFactors = FALSE),
                       balance_table[3:6,],
                       data.frame(label2 = "Education", quota = NA, full_sample = NA, wahlomat_encouragement_no = NA, wahlomat_encouragement_yes = NA, wahlomat_use_no = NA, wahlomat_use_yes = NA, stringsAsFactors = FALSE),
                       balance_table[7:10,])

# add fancy multicol names
addtorow <- list()
addtorow$pos <- list(0)
addtorow$command <- paste0(paste0('& & & \\multicolumn{4}{c}{Wahl-O-Mat...}  ', collapse=''), '\\\\',paste0('\\cmidrule(r){4-5}\\cmidrule(r){6-7}& b4p \'17 & Full &\\multicolumn{2}{c}{Encouragement}  & \\multicolumn{2}{c}{Use}', collapse=''), '\\\\',
                           paste0('Respondent characteristic & Index & sample & No & Yes &No & Yes', collapse=''), '\\\\')

balance_table_xtab <- xtable(balance_table, digits = 0, label = "tab:balance")
caption(balance_table_xtab) <- "Descriptive statistics of respondent characteristics, by subgroup"
print(balance_table_xtab, type = "latex", sanitize.text.function = function(x){x}, size = "footnotesize", table.placement = "t!", add.to.row=addtorow, include.rownames = FALSE, include.colnames = FALSE, caption.placement = "top", file = "../output/wahlomat_balance_table.tex")



